Page({
    data: {
      pet: {
        id: '',
        name: '',
        age: '',
        price: 0,
        img: '',
        description: ''
      },
      isFavorite: false,
      showPopup: false,
      userInfo: {}
    },
  
    onLoad(options) {
      const userInfo = wx.getStorageSync('userInfo');
      this.setData({ userInfo });
      this.fetchPetDetail(options.id);
    },
  
    async fetchPetDetail(id) {
        const userInfo = wx.getStorageSync('userInfo');
        wx.request({
          url: `http://localhost:3000/pets/${id}`,
          method: 'GET',
          success: (res) => {
            if (res.data.code === 200) {
              const pet = res.data.data;
              wx.request({
                url: `http://localhost:3000/favorites/${userInfo.openid}`,
                method: 'GET',
                success: favRes => {
                  const favorites = favRes.data.data || [];
                  const isFavorite = favorites.some(item => item.id === pet.id);
                  this.setData({ pet, isFavorite });
                }
              });
            }
          }
        });
      },
  
    async setPetData(pet) {
      const userInfo = this.data.userInfo;
      let isFavorite = false;
  
      if (userInfo && userInfo.openid) {
        isFavorite = await this.checkIsFavorite(pet.id, userInfo.openid);
      }
  
      this.setData({
        pet,
        isFavorite
      });
    },
  
    checkIsFavorite(petId, userId) {
      return new Promise((resolve) => {
        wx.request({
          url: `http://localhost:3000/favorites/${userId}`,
          method: 'GET',
          success: (res) => {
            if (res.data.code === 200) {
              const petIds = res.data.data.map(p => p.id);
              resolve(petIds.includes(petId));
            } else {
              resolve(false);
            }
          },
          fail: () => {
            resolve(false);
          }
        });
      });
    },
  
    toggleFavorite() {
      const pet = this.data.pet;
      const userInfo = this.data.userInfo;
  
      if (!userInfo || !userInfo.openid) {
        wx.showToast({ title: '请先登录', icon: 'none' });
        return;
      }
  
      const userId = userInfo.openid;
      const isFavorite = this.data.isFavorite;
      const method = isFavorite ? 'DELETE' : 'POST';
  
      wx.request({
        url: 'http://localhost:3000/favorites',
        method,
        header: {
          'Content-Type': 'application/json'
        },
        data: {
          user_id: userId,
          pet_id: pet.id
        },
        success: (res) => {
          if (res.data.code === 200) {
            wx.showToast({
              title: isFavorite ? '已取消收藏' : '已加入收藏',
              icon: isFavorite ? 'none' : 'success'
            });
  
            this.setData({ isFavorite: !isFavorite });
  
            // 更新收藏本地缓存
            let favorites = wx.getStorageSync('favorites') || [];
            if (isFavorite) {
              favorites = favorites.filter(id => id !== pet.id);
            } else {
              if (!favorites.includes(pet.id)) {
                favorites.push(pet.id);
              }
            }
            wx.setStorageSync('favorites', favorites);
  
            // 如果是收藏操作，同步添加到购物车
            if (!isFavorite) {
              const cart = wx.getStorageSync('cart') || [];
              const exists = cart.some(item => item.id === pet.id);
              if (!exists) {
                cart.push({ ...pet, checked: false });
                wx.setStorageSync('cart', cart);
              }
            }
          } else {
            wx.showToast({ title: '同步失败', icon: 'none' });
            console.warn('后端返回失败：', res.data.message);
          }
        },
        fail: (err) => {
          console.error('收藏同步失败：', err);
          wx.showToast({ title: '网络错误', icon: 'none' });
        }
      });
    },
  
    openChatPopup() {
      this.setData({ showPopup: true });
    },
  
    closePopup() {
      this.setData({ showPopup: false });
    },
  
    copyWeChat() {
      wx.setClipboardData({
        data: 'wx123456789',
        success: () => {
          wx.showToast({ title: '微信号已复制', icon: 'success' });
          this.setData({ showPopup: false });
        }
      });
    },
  
    onAdopt() {
        const userInfo = this.data.userInfo;
        if (!userInfo || !userInfo.openid) {
            wx.showToast({ title: '请先登录', icon: 'none' });
            return;
        }
      const pet = this.data.pet;
      if (!pet || !pet.id) return;
      wx.navigateTo({
        url: `/pages/cart/checkout/checkout?pets=${encodeURIComponent(JSON.stringify([pet]))}`
      });
    },
  
    goBack() {
      wx.navigateBack();
    }
  });
  